package cn.itcast.bassm.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class MenuUtil {
	public final static String MENU_CREATE_URL="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

	public static boolean createMenu(String json,String accessToken){
		boolean result = false;
		
		//拼装请求地址
		String urlStr=MENU_CREATE_URL.replace("ACCESS_TOKEN", accessToken);
		String jsonstr=json;
		//调用接口
		String respJson=doPostJsonone(urlStr,jsonstr);
		//解析JSON
		 JsonParser parser = new JsonParser(); // 创建JSON解析器
         JsonObject object = (JsonObject) parser.parse(respJson); // 创建JsonObject对象
         String errMsg=object.get("errmsg").getAsString();
         int errCode = object.get("errcode").getAsInt();
         if(0==errCode){
        	 result = true;
         }else {
        	 result =false;
        	 System.out.println("菜单创建失败");
		}
		return result;
	}
	
    public static  String doPostJsonone(String urlStr, String jsonstr) {
        String result = null;
        HttpPost httpPost = new HttpPost(urlStr);

        try {
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            // httpPost.setHeader("Content-Type", "application/json");
            StringEntity se = new StringEntity(jsonstr, "UTF-8");
            se.setContentType("text/json");
            httpPost.setEntity(se);
            @SuppressWarnings("resource")
            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时

            HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实例
            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
            } else {
              System.out.println("出错了");
            }
        } catch (ConnectTimeoutException e) {
        	System.out.println("出错了");
        } catch (UnsupportedEncodingException e) {
        	System.out.println("出错了");
        } catch (IOException e) {
        	System.out.println("出错了");
        } catch (Exception e) {
        	System.out.println("出错了");
        }

        return result;
    }

}
